﻿namespace SimpleWebServices
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.Threading;

    public static class UriExtensionMethods
    {
        public static Uri ToContentLocation(this Uri obj, string extension)
        {
            return obj.ToContentLocation(Thread.CurrentThread.CurrentUICulture, extension);
        }

        public static Uri ToContentLocation(this Uri obj, CultureInfo language, string extension)
        {
            if (null == obj)
            {
                throw new ArgumentNullException("obj");
            }
            else if (!obj.IsAbsoluteUri)
            {
                throw new ArgumentOutOfRangeException("obj");
            }
            else if (null == extension)
            {
                throw new ArgumentNullException("extension");
            }
            else if (0 == extension.Length)
            {
                throw new ArgumentOutOfRangeException("extension");
            }
            else if (null == language)
            {
                throw new ArgumentNullException("language");
            }
            else if (CultureInfo.InvariantCulture == language)
            {
                throw new ArgumentOutOfRangeException("language");
            }

            string path = obj.AbsolutePath;
            if (path.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
            {
                path = path.Substring(0, path.Length - extension.Length);
            }

            if (path.EndsWith("." + language.Name, StringComparison.OrdinalIgnoreCase))
            {
                path = path.Substring(0, path.Length - (language.Name.Length + 1));
            }

            return new Uri(obj.AbsoluteUri.Replace(obj.AbsolutePath, path));
        }

        [SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads", Justification = "It does.")]
        public static Uri ToUri(this Uri obj, string relativeUri)
        {
            return new Uri(obj, new Uri(relativeUri, UriKind.Relative));
        }

        public static Uri ToUri(this Uri obj, Uri relativeUri)
        {
            if (null == relativeUri)
            {
                throw new ArgumentNullException("obj");
            }
            else if (relativeUri.IsAbsoluteUri)
            {
                throw new ArgumentOutOfRangeException("relativeUri");
            }

            return new Uri(obj, relativeUri);
        }
    }
}